package com.lenovo.redission.redission.config.redission;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.TransportMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Objects;

/**
 * <p>
 * Description: 配置redis
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author 赵希坤 zhaoxk
 * @date 2021/5/28 4:27 下午
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.redis", value = "enabled", havingValue = "true")
@EnableConfigurationProperties(RedissionProperties.class)
public class RedissonConfiguration {

    @Autowired
    private RedissionProperties redisProperties;

    private Logger logger = LogManager.getLogger(this.getClass());

    @Bean(name = "redissonConfig")
    public Config redissonConfig() {
        Config config = new Config();
        String osName = Objects.toString(System.getProperties().getProperty("os.name"), "");
        if (osName.toLowerCase().contains("linux")) {
            config.setTransportMode(TransportMode.EPOLL);
        }
        //默认锁超时时间 lockWatchdogTimeout = 30 * 1000
        config.setLockWatchdogTimeout(30);
        String prefix = "redis://";
        config.useSingleServer()
                .setAddress(prefix + redisProperties.getHost() + ":" + redisProperties.getPort())
                .setConnectTimeout(redisProperties.getTimeOut())
                .setDatabase(redisProperties.getDatabase());
        if (StringUtils.isNotBlank(redisProperties.getPassword())) {
            config.useSingleServer().setPassword(redisProperties.getPassword());
        }
        return config;
    }

    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson(@Qualifier(value = "redissonConfig") Config redissonConfig) throws IOException {
        logger.info("create RedissonClient, config is : {}", redissonConfig);
        return Redisson.create(redissonConfig);
    }

}
